﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace _51_AOP.Utility.Filter
{
    public class CustomAsyncResourceFilterAttribute : Attribute, IAsyncResourceFilter
    {
        private static Dictionary<string, object> CacheDictonary = new Dictionary<string, object>();
        /// <summary>
        ///  资源执行的时候
        /// </summary>
        /// <param name="context"></param>
        /// <param name="next"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task OnResourceExecutionAsync(ResourceExecutingContext context, ResourceExecutionDelegate next)
        {
            Console.WriteLine("CustomAsyncResourceFilterAttribute资源执行的时候--开始");
            var key = context.HttpContext.Request.Path;
            if (CacheDictonary.ContainsKey(key))
            {
                context.Result = (IActionResult)CacheDictonary[key];  // 只要给Result赋值了，就会中断往后执行，直接返回给调用方,不执行Action方法
            }
            else {
                ResourceExecutedContext rs = await next.Invoke();  // 这个是去执行控制器和Action方法的
                CacheDictonary[key] = rs.Result;
            }
            Console.WriteLine("CustomAsyncResourceFilterAttribute资源执行的时候--结尾");
        }
    }
}
